//! Epic 6: 异步处理引擎 - 验收测试
//!
//! 本文件包含 Epic 6 的 P0 验收测试，遵循 ATDD 红-绿-重构循环。
//!
//! ## 测试场景
//!
//! - AC-6.1: 异步消息队列
//! - AC-6.2: 后台写入线程 (Story 6.2)
//! - AC-6.3: 队列大小配置 (Story 6.3)
//! - AC-6.4: 背压策略 (Story 6.4)

mod common;

use log4r::{Level, LogEvent};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::thread;
use std::time::Duration;

// ============================================================================
// AC-6.1: 异步消息队列
// ============================================================================

/// UT-601: LogChannel::new() 创建指定容量通道
///
/// GIVEN: 指定队列容量为 100
/// WHEN: 创建 LogChannel
/// THEN: 通道容量为 100
#[test]
fn test_log_channel_new_with_capacity() {
    use log4r::async_rt::LogChannel;

    // GIVEN: 指定容量
    let capacity = 100;

    // WHEN: 创建通道
    let channel = LogChannel::new(capacity);

    // THEN: 通道创建成功，容量正确
    assert_eq!(channel.capacity(), Some(capacity));
    assert_eq!(channel.len(), 0);
    assert!(!channel.is_full());
}

/// UT-602: LogChannel::with_default_capacity() 使用默认容量 10000
///
/// GIVEN: 未指定队列容量
/// WHEN: 创建默认 LogChannel
/// THEN: 通道容量为 10000
#[test]
fn test_log_channel_default_capacity() {
    use log4r::async_rt::{LogChannel, DEFAULT_QUEUE_SIZE};

    // WHEN: 创建默认通道
    let channel = LogChannel::with_default_capacity();

    // THEN: 默认容量为 10000
    assert_eq!(channel.capacity(), Some(DEFAULT_QUEUE_SIZE));
    assert_eq!(DEFAULT_QUEUE_SIZE, 10000);
}

/// UT-603: LogChannel::send() 队列未满时非阻塞
///
/// GIVEN: 队列未满
/// WHEN: 发送日志事件
/// THEN: 发送立即返回，不阻塞
#[test]
fn test_log_channel_send_non_blocking_when_not_full() {
    use log4r::async_rt::LogChannel;

    // GIVEN: 创建通道，队列未满
    let channel = LogChannel::new(100);
    let event = LogEvent::new(Level::Info, "test", "test message");

    // WHEN: 发送事件
    let start = std::time::Instant::now();
    let result = channel.send(event);
    let elapsed = start.elapsed();

    // THEN: 发送成功且立即返回（< 1ms）
    assert!(result.is_ok());
    assert!(elapsed < Duration::from_millis(1), "发送应该是非阻塞的");
    assert_eq!(channel.len(), 1);
}

/// UT-604: LogChannel::try_send() 非阻塞发送
///
/// GIVEN: 队列未满
/// WHEN: 使用 try_send 发送
/// THEN: 立即返回 Ok
#[test]
fn test_log_channel_try_send_success() {
    use log4r::async_rt::LogChannel;

    // GIVEN: 创建通道
    let channel = LogChannel::new(10);
    let event = LogEvent::new(Level::Debug, "test", "debug message");

    // WHEN: try_send
    let result = channel.try_send(event);

    // THEN: 成功
    assert!(result.is_ok());
}

/// UT-605: LogChannel::try_send() 队列满时返回错误
///
/// GIVEN: 队列已满
/// WHEN: 使用 try_send 发送
/// THEN: 立即返回 Err
#[test]
fn test_log_channel_try_send_full_returns_error() {
    use log4r::async_rt::LogChannel;

    // GIVEN: 创建小容量通道并填满
    let channel = LogChannel::new(2);
    let _ = channel.send(LogEvent::new(Level::Info, "test", "msg1"));
    let _ = channel.send(LogEvent::new(Level::Info, "test", "msg2"));
    assert!(channel.is_full());

    // WHEN: try_send 到满队列
    let event = LogEvent::new(Level::Info, "test", "msg3");
    let result = channel.try_send(event);

    // THEN: 返回错误
    assert!(result.is_err());
}

/// IT-601: 多线程并发发送无数据丢失
///
/// GIVEN: 多个线程同时发送日志
/// WHEN: 并发发送 1000 条日志
/// THEN: 所有日志都成功入队，无数据丢失
#[test]
fn test_log_channel_concurrent_send_no_data_loss() {
    use log4r::async_rt::LogChannel;

    // GIVEN: 创建足够大的通道
    let channel = Arc::new(LogChannel::new(10000));
    let send_count = Arc::new(AtomicUsize::new(0));
    let thread_count = 10;
    let messages_per_thread = 100;

    // WHEN: 多线程并发发送
    let mut handles = vec![];
    for thread_id in 0..thread_count {
        let ch = Arc::clone(&channel);
        let counter = Arc::clone(&send_count);

        let handle = thread::spawn(move || {
            for i in 0..messages_per_thread {
                // 使用 String 而非 &str 避免生命周期问题
                let target = format!("thread-{}", thread_id);
                let message = format!("message-{}", i);
                let event = LogEvent::new(Level::Info, target, message);
                if ch.send(event).is_ok() {
                    counter.fetch_add(1, Ordering::SeqCst);
                }
            }
        });
        handles.push(handle);
    }

    // 等待所有线程完成
    for handle in handles {
        handle.join().expect("线程应该正常完成");
    }

    // THEN: 所有消息都成功发送
    let total_expected = thread_count * messages_per_thread;
    assert_eq!(send_count.load(Ordering::SeqCst), total_expected);
    assert_eq!(channel.len(), total_expected);
}

/// UT-606: LogChannel 实现 Send + Sync
///
/// GIVEN: LogChannel 类型
/// WHEN: 编译时检查
/// THEN: 实现 Send + Sync trait
#[test]
fn test_log_channel_is_send_sync() {
    use log4r::async_rt::LogChannel;

    fn assert_send<T: Send>() {}
    fn assert_sync<T: Sync>() {}

    assert_send::<LogChannel>();
    assert_sync::<LogChannel>();
}

/// UT-607: LogChannel::sender() 返回可克隆的发送端
///
/// GIVEN: 一个 LogChannel
/// WHEN: 调用 sender() 获取发送端
/// THEN: 可以使用发送端发送消息
#[test]
fn test_log_channel_sender_clone() {
    use log4r::async_rt::LogChannel;

    // GIVEN: 创建通道
    let channel = LogChannel::new(100);

    // WHEN: 获取 sender 并发送
    let sender = channel.sender();
    let event = LogEvent::new(Level::Info, "test", "via sender");
    let result = sender.try_send(event);

    // THEN: 发送成功
    assert!(result.is_ok());
    assert_eq!(channel.len(), 1);
}

/// UT-608: LogChannel::receiver() 返回接收端引用
///
/// GIVEN: 一个 LogChannel 并发送消息
/// WHEN: 调用 receiver() 获取接收端
/// THEN: 可以接收消息
#[test]
fn test_log_channel_receiver_reference() {
    use log4r::async_rt::LogChannel;

    // GIVEN: 创建通道并发送消息
    let channel = LogChannel::new(100);
    let event = LogEvent::new(Level::Info, "test", "to receive");
    channel.try_send(event).unwrap_or(());

    // WHEN: 获取 receiver 并接收
    let receiver = channel.receiver();
    let received = receiver.try_recv();

    // THEN: 成功接收
    assert!(received.is_ok());
    let received_event = received.unwrap_or_else(|_| LogEvent::new(Level::Error, "", ""));
    assert_eq!(received_event.message, "to receive");
    assert!(channel.is_empty());
}

/// UT-609: LogChannel 队列状态查询方法
///
/// GIVEN: 一个 LogChannel
/// WHEN: 查询队列状态
/// THEN: len(), is_empty(), is_full(), capacity() 返回正确值
#[test]
fn test_log_channel_status_methods() {
    use log4r::async_rt::LogChannel;

    // GIVEN: 创建容量为 3 的通道
    let channel = LogChannel::new(3);

    // THEN: 初始状态
    assert!(channel.is_empty());
    assert!(!channel.is_full());
    assert_eq!(channel.len(), 0);
    assert_eq!(channel.capacity(), Some(3));

    // WHEN: 添加消息
    channel
        .try_send(LogEvent::new(Level::Info, "test", "msg1"))
        .unwrap_or(());
    channel
        .try_send(LogEvent::new(Level::Info, "test", "msg2"))
        .unwrap_or(());
    channel
        .try_send(LogEvent::new(Level::Info, "test", "msg3"))
        .unwrap_or(());

    // THEN: 队列已满
    assert!(channel.is_full());
    assert!(!channel.is_empty());
    assert_eq!(channel.len(), 3);
}

// ============================================================================
// AC-6.2: 后台写入线程 (Story 6.2)
// ============================================================================

use log4r::appender::Appender;
use log4r::async_rt::{Worker, WorkerConfig, DEFAULT_BATCH_SIZE};
use log4r::Log4rError;
use std::sync::Mutex;

/// 测试用 Mock Appender
struct TestAppender {
    events: Arc<Mutex<Vec<String>>>,
    flush_count: Arc<Mutex<usize>>,
    close_count: Arc<Mutex<usize>>,
}

impl TestAppender {
    fn new() -> Self {
        Self {
            events: Arc::new(Mutex::new(Vec::new())),
            flush_count: Arc::new(Mutex::new(0)),
            close_count: Arc::new(Mutex::new(0)),
        }
    }

    fn events_clone(&self) -> Arc<Mutex<Vec<String>>> {
        Arc::clone(&self.events)
    }

    fn flush_count_clone(&self) -> Arc<Mutex<usize>> {
        Arc::clone(&self.flush_count)
    }

    fn close_count_clone(&self) -> Arc<Mutex<usize>> {
        Arc::clone(&self.close_count)
    }
}

impl Appender for TestAppender {
    fn write(&self, event: &LogEvent) -> Result<(), Log4rError> {
        self.events
            .lock()
            .map_err(|_| Log4rError::appender("TestAppender", "获取锁失败"))?
            .push(format!("[{}] {}", event.level, event.message));
        Ok(())
    }

    fn flush(&self) -> Result<(), Log4rError> {
        let mut count = self
            .flush_count
            .lock()
            .map_err(|_| Log4rError::appender("TestAppender", "获取锁失败"))?;
        *count += 1;
        Ok(())
    }

    fn close(&self) -> Result<(), Log4rError> {
        let mut count = self
            .close_count
            .lock()
            .map_err(|_| Log4rError::appender("TestAppender", "获取锁失败"))?;
        *count += 1;
        Ok(())
    }
}

/// IT-6.2-001: Worker 启动并消费队列事件
///
/// GIVEN: 异步模式启用
/// WHEN: 日志系统初始化
/// THEN: 启动一个后台写入线程，消费队列事件
#[test]
fn test_worker_starts_and_consumes_events() {
    use log4r::async_rt::LogChannel;

    // GIVEN: 创建通道和 Appender
    let channel = LogChannel::new(1000);
    let appender = TestAppender::new();
    let events_ref = appender.events_clone();
    let appenders: Vec<Arc<dyn Appender>> = vec![Arc::new(appender)];

    // WHEN: 启动 Worker
    let receiver = channel.receiver().clone();
    let fallback: Arc<dyn Appender> = Arc::new(TestAppender::new());
    let worker = Worker::start(
        receiver,
        appenders,
        fallback,
        WorkerConfig::default(),
        "test_app".to_string(),
    );

    // 发送事件
    for i in 0..5 {
        let event = LogEvent::new(Level::Info, "test", format!("msg{}", i));
        channel.send(event).unwrap_or(());
    }

    // 给 Worker 时间处理
    thread::sleep(Duration::from_millis(100));

    // 关闭 Worker
    drop(channel); // 断开发送端
    let result = worker.shutdown();

    // THEN: 所有事件应被处理
    assert!(result.is_ok());
    let events = events_ref.lock().unwrap_or_else(|e| e.into_inner());
    assert_eq!(events.len(), 5);
}

/// IT-6.2-002: Worker 批量处理后 flush
///
/// GIVEN: 批量写入配置为 100
/// WHEN: 发送日志事件
/// THEN: 每批处理后调用 flush
#[test]
fn test_worker_flushes_after_batch() {
    use log4r::async_rt::LogChannel;

    // GIVEN: 创建通道和 Appender
    let channel = LogChannel::new(1000);
    let appender = TestAppender::new();
    let flush_count_ref = appender.flush_count_clone();
    let appenders: Vec<Arc<dyn Appender>> = vec![Arc::new(appender)];

    // WHEN: 启动 Worker 并发送事件
    let receiver = channel.receiver().clone();
    let fallback: Arc<dyn Appender> = Arc::new(TestAppender::new());
    let worker = Worker::start(
        receiver,
        appenders,
        fallback,
        WorkerConfig::default(),
        "test_app".to_string(),
    );

    // 发送少量事件（不足一批）
    for i in 0..10 {
        let event = LogEvent::new(Level::Info, "test", format!("msg{}", i));
        channel.send(event).unwrap_or(());
    }

    // 给 Worker 时间处理
    thread::sleep(Duration::from_millis(100));

    // 关闭 Worker
    drop(channel);
    let result = worker.shutdown();

    // THEN: flush 应被调用
    assert!(result.is_ok());
    let flush_count = *flush_count_ref.lock().unwrap_or_else(|e| e.into_inner());
    assert!(flush_count >= 1, "flush 应至少被调用一次");
}

/// IT-6.2-003: Worker 关闭时队列清空
///
/// GIVEN: 队列中有剩余事件
/// WHEN: 调用 shutdown
/// THEN: 等待队列中剩余事件处理完成
#[test]
fn test_worker_shutdown_waits_for_queue_drain() {
    use log4r::async_rt::LogChannel;

    // GIVEN: 创建通道和 Appender
    let channel = LogChannel::new(1000);
    let appender = TestAppender::new();
    let events_ref = appender.events_clone();
    let close_count_ref = appender.close_count_clone();
    let appenders: Vec<Arc<dyn Appender>> = vec![Arc::new(appender)];

    // WHEN: 启动 Worker
    let receiver = channel.receiver().clone();
    let fallback: Arc<dyn Appender> = Arc::new(TestAppender::new());
    let worker = Worker::start(
        receiver,
        appenders,
        fallback,
        WorkerConfig::default(),
        "test_app".to_string(),
    );

    // 发送事件
    for i in 0..20 {
        let event = LogEvent::new(Level::Info, "test", format!("drain{}", i));
        channel.send(event).unwrap_or(());
    }

    // 立即关闭（不等待处理）
    drop(channel);
    let result = worker.shutdown();

    // THEN: 关闭成功，所有事件被处理，close 被调用
    assert!(result.is_ok());
    let events = events_ref.lock().unwrap_or_else(|e| e.into_inner());
    assert_eq!(events.len(), 20, "所有事件应被处理");
    let close_count = *close_count_ref.lock().unwrap_or_else(|e| e.into_inner());
    assert_eq!(close_count, 1, "close 应被调用一次");
}

/// IT-6.2-004: Appender 失败时错误隔离
///
/// GIVEN: 一个会失败的 Appender 和一个正常的 Appender
/// WHEN: 写入日志
/// THEN: 失败的 Appender 不影响其他 Appender
#[test]
fn test_appender_failure_isolation() {
    use log4r::async_rt::LogChannel;

    /// 会失败的 Appender
    struct FailingAppender;

    impl Appender for FailingAppender {
        fn write(&self, _event: &LogEvent) -> Result<(), Log4rError> {
            Err(Log4rError::appender("FailingAppender", "模拟失败"))
        }
        fn flush(&self) -> Result<(), Log4rError> {
            Ok(())
        }
        fn close(&self) -> Result<(), Log4rError> {
            Ok(())
        }
    }

    // GIVEN: 一个失败的和一个正常的 Appender
    let channel = LogChannel::new(1000);
    let normal_appender = TestAppender::new();
    let events_ref = normal_appender.events_clone();
    let appenders: Vec<Arc<dyn Appender>> =
        vec![Arc::new(FailingAppender), Arc::new(normal_appender)];

    // WHEN: 启动 Worker 并发送事件
    let receiver = channel.receiver().clone();
    let fallback: Arc<dyn Appender> = Arc::new(TestAppender::new());
    let worker = Worker::start(
        receiver,
        appenders,
        fallback,
        WorkerConfig::default(),
        "test_app".to_string(),
    );

    for i in 0..3 {
        let event = LogEvent::new(Level::Error, "test", format!("error{}", i));
        channel.send(event).unwrap_or(());
    }

    thread::sleep(Duration::from_millis(100));
    drop(channel);
    let result = worker.shutdown();

    // THEN: 正常的 Appender 应收到所有事件
    assert!(result.is_ok());
    let events = events_ref.lock().unwrap_or_else(|e| e.into_inner());
    assert_eq!(events.len(), 3, "正常 Appender 应收到所有事件");
}

/// UT-6.2-001: WorkerConfig 默认值
///
/// GIVEN: 未指定配置
/// WHEN: 创建默认 WorkerConfig
/// THEN: batch_size = 100
#[test]
fn test_worker_config_defaults() {
    let config = WorkerConfig::default();
    assert_eq!(config.batch_size, DEFAULT_BATCH_SIZE);
    assert_eq!(config.batch_size, 100);
}

/// UT-6.2-002: Worker 实现 Send
///
/// GIVEN: Worker 类型
/// WHEN: 编译时检查
/// THEN: 实现 Send trait
#[test]
fn test_worker_is_send() {
    fn assert_send<T: Send>() {}
    assert_send::<Worker>();
}

// ============================================================================
// AC-6.3: 队列大小配置 (Story 6.3)
// ============================================================================

use log4r::config::AsyncConfig;

/// IT-6.3-001: 端到端配置加载和通道创建 (AC-6.3.1)
///
/// GIVEN: 配置文件指定 queue_size = 50000
/// WHEN: 初始化异步日志系统
/// THEN: 创建大小为 50000 的 bounded channel
#[test]
fn test_async_config_to_channel_integration() {
    use log4r::async_rt::LogChannel;

    // GIVEN: 从 TOML 解析配置
    let toml_str = r#"
enabled = true
queue_size = 50000
"#;
    let config: AsyncConfig = toml::from_str(toml_str).unwrap_or_default();

    // WHEN: 使用配置值创建 LogChannel
    let channel = LogChannel::new(config.queue_size);

    // THEN: 通道容量应为 50000
    assert_eq!(channel.capacity(), Some(50000));
}

/// IT-6.3-002: 默认配置创建默认容量通道 (AC-6.3.2)
///
/// GIVEN: 未配置 queue_size
/// WHEN: 使用默认 AsyncConfig 创建通道
/// THEN: 通道容量为 10000
#[test]
fn test_default_async_config_to_channel() {
    use log4r::async_rt::LogChannel;

    // GIVEN: 默认配置
    let config = AsyncConfig::default();

    // WHEN: 使用配置值创建 LogChannel
    let channel = LogChannel::new(config.queue_size);

    // THEN: 通道容量应为默认值 10000
    assert_eq!(channel.capacity(), Some(10000));
}

/// IT-6.3-003: 配置验证集成 (AC-6.3.3)
///
/// GIVEN: queue_size = 0 的配置
/// WHEN: 验证配置
/// THEN: 返回 ConfigError
#[test]
fn test_async_config_validation_integration() {
    // GIVEN: 无效配置
    let config = AsyncConfig {
        enabled: true,
        queue_size: 0,
        ..Default::default()
    };

    // WHEN: 验证配置
    let result = config.validate();

    // THEN: 应返回错误
    assert!(result.is_err());
    let err_msg = result.unwrap_err().to_string();
    assert!(err_msg.contains("queue_size"));
}

/// IT-6.3-004: 完整 Log4rConfig 解析 queue_size (AC-6.3.1)
///
/// GIVEN: 完整的 Log4rConfig TOML
/// WHEN: 解析配置
/// THEN: async_config.queue_size 正确解析
#[test]
fn test_full_config_queue_size_parsing() {
    use log4r::config::Log4rConfig;

    // GIVEN: 完整配置 TOML
    let toml_str = r#"
level = "debug"
app_name = "test_app"

[async]
enabled = true
queue_size = 25000
"#;

    // WHEN: 解析配置
    let config: Log4rConfig = toml::from_str(toml_str).unwrap_or_default();

    // THEN: queue_size 应正确解析
    assert_eq!(config.async_config.queue_size, 25000);
    assert!(config.async_config.enabled);
}

/// IT-6.3-005: 边界值 queue_size = 1 创建通道 (AC-6.3.1)
///
/// GIVEN: queue_size = 1
/// WHEN: 创建 LogChannel
/// THEN: 通道容量为 1，可正常使用
#[test]
fn test_min_queue_size_channel() {
    use log4r::async_rt::LogChannel;

    // GIVEN: 最小有效配置
    let config = AsyncConfig {
        enabled: true,
        queue_size: 1,
        ..Default::default()
    };
    assert!(config.validate().is_ok());

    // WHEN: 创建通道
    let channel = LogChannel::new(config.queue_size);

    // THEN: 通道可正常使用
    assert_eq!(channel.capacity(), Some(1));
    let event = LogEvent::new(Level::Info, "test", "single");
    assert!(channel.try_send(event).is_ok());
    assert!(channel.is_full());
}

/// IT-6.3-006: 大 queue_size 创建通道 (AC-6.3.4)
///
/// GIVEN: queue_size = 2000000 (超过警告阈值)
/// WHEN: 验证配置并创建通道
/// THEN: 验证通过（输出警告），通道创建成功
#[test]
fn test_large_queue_size_channel() {
    use log4r::async_rt::LogChannel;

    // GIVEN: 大队列配置
    let config = AsyncConfig {
        enabled: true,
        queue_size: 2_000_000,
        ..Default::default()
    };

    // WHEN: 验证配置
    let result = config.validate();

    // THEN: 验证通过（警告输出到 stderr）
    assert!(result.is_ok());

    // 创建通道（实际测试中可能因内存限制而跳过）
    // 这里只验证小容量以避免内存问题
    let small_channel = LogChannel::new(1000);
    assert_eq!(small_channel.capacity(), Some(1000));
}

// ============================================================================
// AC-6.4: 背压策略 (Story 6.4)
// ============================================================================

use log4r::config::BackpressureStrategy;

/// IT-6.4-001: 队列满时阻塞发送 (AC-6.4.1)
///
/// GIVEN: 异步队列已满且背压策略为 Block
/// WHEN: 发送新日志事件
/// THEN: 发送操作阻塞等待队列有空间
#[test]
fn test_block_backpressure_blocks_when_full() {
    use log4r::async_rt::LogChannel;
    use std::sync::atomic::AtomicBool;

    // GIVEN: 创建小容量队列并填满
    let channel = Arc::new(LogChannel::new(2));
    channel
        .try_send(LogEvent::new(Level::Info, "test", "msg1"))
        .unwrap_or(());
    channel
        .try_send(LogEvent::new(Level::Info, "test", "msg2"))
        .unwrap_or(());
    assert!(channel.is_full());

    // 标记发送是否完成
    let send_completed = Arc::new(AtomicBool::new(false));
    let send_completed_clone = Arc::clone(&send_completed);

    // WHEN: 在另一个线程发送（应该阻塞）
    let channel_clone = Arc::clone(&channel);
    let handle = thread::spawn(move || {
        let event = LogEvent::new(Level::Info, "test", "blocked_msg");
        let result = channel_clone.send(event);
        send_completed_clone.store(true, Ordering::SeqCst);
        result
    });

    // 等待一小段时间，验证发送被阻塞
    thread::sleep(Duration::from_millis(50));
    assert!(
        !send_completed.load(Ordering::SeqCst),
        "发送应该被阻塞，不应完成"
    );

    // 消费一条消息，释放空间
    let _ = channel.receiver().try_recv();

    // THEN: 阻塞的发送应该继续执行
    let result = handle.join().expect("线程应正常完成");
    assert!(result.is_ok(), "发送应该成功");
    assert!(send_completed.load(Ordering::SeqCst), "发送应该已完成");
}

/// IT-6.4-002: 阻塞解除后继续发送 (AC-6.4.2)
///
/// GIVEN: 队列满导致阻塞
/// WHEN: 后台线程消费事件释放空间
/// THEN: 阻塞的发送操作继续执行
#[test]
fn test_block_backpressure_resumes_after_space_available() {
    use log4r::async_rt::LogChannel;

    // GIVEN: 创建小容量队列
    let channel = Arc::new(LogChannel::new(1));
    channel
        .try_send(LogEvent::new(Level::Info, "test", "initial"))
        .unwrap_or(());
    assert!(channel.is_full());

    // WHEN: 启动消费者线程
    let channel_consumer = Arc::clone(&channel);
    let consumer_handle = thread::spawn(move || {
        thread::sleep(Duration::from_millis(30));
        // 消费消息释放空间
        let _ = channel_consumer.receiver().try_recv();
    });

    // 发送新消息（会先阻塞，然后继续）
    let start = std::time::Instant::now();
    let event = LogEvent::new(Level::Info, "test", "after_block");
    let result = channel.send(event);
    let elapsed = start.elapsed();

    consumer_handle.join().expect("消费者线程应正常完成");

    // THEN: 发送成功，且耗时应大于消费者等待时间
    assert!(result.is_ok());
    assert!(
        elapsed >= Duration::from_millis(25),
        "发送应该被阻塞一段时间"
    );
}

/// IT-6.4-003: 背压计数器递增 (AC-6.4.3)
///
/// GIVEN: 队列满时发送
/// WHEN: 多次触发背压
/// THEN: 背压计数器正确递增
#[test]
fn test_backpressure_counter_increments() {
    use log4r::async_rt::LogChannel;

    // GIVEN: 创建小容量队列
    let channel = Arc::new(LogChannel::new(1));

    // 初始背压计数为 0
    assert_eq!(channel.backpressure_count(), 0);

    // WHEN: 触发多次背压
    for i in 0..3 {
        // 填满队列
        channel
            .try_send(LogEvent::new(Level::Info, "test", format!("fill_{}", i)))
            .unwrap_or(());

        // 在另一个线程发送（触发背压）
        let channel_clone = Arc::clone(&channel);
        let handle = thread::spawn(move || {
            let event = LogEvent::new(Level::Info, "test", format!("blocked_{}", i));
            channel_clone.send(event)
        });

        // 等待发送线程阻塞
        thread::sleep(Duration::from_millis(20));

        // 消费消息释放空间
        let _ = channel.receiver().try_recv();
        let _ = channel.receiver().try_recv();

        let _ = handle.join().expect("发送线程应正常完成");
    }

    // THEN: 背压计数应为 3
    assert_eq!(channel.backpressure_count(), 3);
}

/// IT-6.4-004: 端到端背压流程 (AC-6.4.1, AC-6.4.2)
///
/// GIVEN: 配置 backpressure = "block"
/// WHEN: 高负载发送日志
/// THEN: 系统正常运行，无数据丢失
#[test]
fn test_end_to_end_backpressure_flow() {
    use log4r::async_rt::LogChannel;
    use std::sync::atomic::AtomicBool;

    // GIVEN: 创建小容量队列模拟高负载
    let channel = LogChannel::new(5);
    let sender = channel.sender();
    let receiver = channel.receiver().clone();
    let total_messages = 20;
    let received_count = Arc::new(AtomicUsize::new(0));
    let stop_flag = Arc::new(AtomicBool::new(false));

    // 启动消费者线程
    let received_count_clone = Arc::clone(&received_count);
    let stop_flag_clone = Arc::clone(&stop_flag);
    let consumer_handle = thread::spawn(move || {
        while !stop_flag_clone.load(Ordering::SeqCst) {
            match receiver.try_recv() {
                Ok(_) => {
                    received_count_clone.fetch_add(1, Ordering::SeqCst);
                    // 模拟处理延迟
                    thread::sleep(Duration::from_millis(2));
                }
                Err(_) => {
                    thread::sleep(Duration::from_millis(1));
                }
            }
        }
        // 消费剩余消息
        while receiver.try_recv().is_ok() {
            received_count_clone.fetch_add(1, Ordering::SeqCst);
        }
    });

    // WHEN: 快速发送多条消息
    for i in 0..total_messages {
        let event = LogEvent::new(Level::Info, "test", format!("msg_{}", i));
        sender.send(event).expect("发送应成功");
    }

    // 等待消费完成
    thread::sleep(Duration::from_millis(150));
    stop_flag.store(true, Ordering::SeqCst);
    consumer_handle.join().expect("消费者线程应正常完成");

    // THEN: 所有消息都被接收，无数据丢失
    assert_eq!(
        received_count.load(Ordering::SeqCst),
        total_messages,
        "所有消息应被接收"
    );
}

/// UT-6.4-001: BackpressureStrategy 默认值为 Block (AC-6.4.4)
#[test]
fn test_backpressure_strategy_default_is_block() {
    let strategy = BackpressureStrategy::default();
    assert_eq!(strategy, BackpressureStrategy::Block);
}

/// UT-6.4-002: TOML 解析 backpressure 配置 (AC-6.4.4)
#[test]
fn test_backpressure_config_toml_parsing() {
    // GIVEN: 包含 backpressure 的完整配置
    let toml_str = r#"
enabled = true
queue_size = 10000
backpressure = "block"
"#;

    // WHEN: 解析配置
    let config: AsyncConfig = toml::from_str(toml_str).unwrap_or_default();

    // THEN: backpressure 应正确解析
    assert_eq!(config.backpressure, BackpressureStrategy::Block);
}

/// UT-6.4-003: AsyncConfig 默认 backpressure = Block (AC-6.4.4)
#[test]
fn test_async_config_default_backpressure() {
    let config = AsyncConfig::default();
    assert_eq!(config.backpressure, BackpressureStrategy::Block);
}
